<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/3/28
 * Time: 14:31
 */

namespace common\components\extenders;


use common\components\helpers\Util;
use common\components\services\customer\Createcard;
use common\models\datas\Cate;
use common\models\datas\Customer;
use common\models\datas\CustomerBranchaccount;
use common\models\datas\IsuserInfo;
use common\models\datas\LoginAuth;
use common\models\datas\Student;
use frontend\models\datas\ClassLesson;
use frontend\models\datas\ClassManage;
use frontend\models\datas\Goods;
use frontend\models\datas\GoodsAttr;
use frontend\models\datas\GoodsGroup;
use frontend\models\datas\LessonStudent;
use frontend\models\datas\Mechanic;
use frontend\models\datas\Orders;
use frontend\models\datas\OrdersItems;
use frontend\models\datas\StudentCheck;
use frontend\models\datas\Teacher;
use yii\db\Query;
use common\components\helpers\Fun;
use yii\base\Component;
use yii\web\BadRequestHttpException;
use common\models\datas\CardAttr;
use common\models\datas\Site;
use zhtfrontend\models\datas\GoodsTeacher;

class CheckoutManage extends Component
{
    public $weburl;

    public $wechaturl;

    public $appurl;

    public function run()
    {

    }


    /**
     *获取登陆端信息
     *
     */
    public function getClients()
    {

    }

    /**
     * 获取用户收货地址
     * 根据购物车customer_id查找dmd_customer_address表中该用户地址
     * @param $customer_id int
     * @return array
     *
     */
    public function getAddress($customer_id)
    {
        //获取数据库
        $siteId = (int)Fun::getSiteId();
        $customer = (new Query())->select("*")->from("{{%customer_address}}")->where(['customer_id' => $customer_id])->all(Fun::getSiteDatabases($siteId));

        return $customer;
    }

    /**
     * 获取学员信息
     * 根据购物车customer_id查询dmd_student表 学员信息
     * @param $customer_id int
     * @return array
     *
     */
    public function getStudents($customer_id)
    {
        //获取数据库
        $siteId = (int)Fun::getSiteId();
        $student = (new Query())->select("*")->from("{{%student}}")->where(['customer_id' => $customer_id])->all(Fun::getSiteDatabases($siteId));

        return $student;
    }

    /**
     * 获取用户优惠券信息
     * 根据购物车customer_id查询dmd_customer_coupon表 用户优惠信息
     * @param $customer_id int
     * @return array
     *
     */
    public function getCustomerCoupon($customer_id)
    {
        //获取数据库
        $siteId = (int)Fun::getSiteId();
        $coupon = (new Query())->select("*")->from("{{%customer_coupons}}")->where(['customer_id' => $customer_id])->all(Fun::getSiteDatabases($siteId));

        return $coupon;
    }

    /**
     * 按时间获取可用的活动 当前时间在活动时间范围内的
     *
     */
    public function getActives()
    {
        //获取数据库
        //$siteId = (int)\Yii::$app->request->cookies->get('site_id')->value;
        $siteId = 2;

        $time = time();
        $actives = (new Query())->select("*")->from("{{%activity}}")
            ->where(['>', 'start_time', $time])
            ->andwhere(['<', 'end_time', $time])
            ->andwhere(['status' => 1])
            ->andWhere(['is_delete' => 0])
            ->all(Fun::getSiteDatabases($siteId));

        return $actives;
    }

    /*
     * 获取某种类型符合要求的活动
     *
     */
    public function getActivesbyType($active_type)
    {
        //获取数据库
        //$siteId = (int)\Yii::$app->request->cookies->get('site_id')->value;
        $siteId = 2;

        $time = time();
        $actives = (new Query())->select("*")->from("{{%activity}}")
            ->where(['<', 'start_time', $time])
            ->andwhere(['>', 'end_time', $time])
            ->andWhere(['type' => $active_type])
            ->andwhere(['status' => 1])
            ->andWhere(['is_delete' => 0])
            ->all(Fun::getSiteDatabases($siteId));
        return $actives;
    }

    /**
     * 获取订单类型
     * 根据购物车提交信息中customer_id查询商品类型 组装类型数组
     * 返回['类型'=>cart_id]
     * @param $customer_id int
     * @return array
     *
     */
    public function getOrderTypes($customer_id)
    {
        /**$cart = new CartManage();
         *
         * $cartids = $cart->getOrderGoodId($customer_id);
         * $dataType = [];
         * $data = [];
         * foreach ($cartids as $v) {
         * $dataCart = $cart->getOneCart($v);
         *
         * if(in_array($dataCart['type_id'],$dataType)){
         * $data[$dataCart['type_id']][] = $v;
         * }else{
         * $dataType[] = $dataCart['type_id'];
         * $data[$dataCart['type_id']][] = $v;
         * }
         * }
         *
         * return $data;*/
        $cart = new CartManage();

        $cartids = $cart->getOrderGoodId($customer_id);
        $dataType = [];
        $data = [];
        foreach ($cartids as $v) {
            $dataCart = $cart->getOneCart($v);
            $type = $dataCart[0]['type_id'];//根据dataCart的结果来随机应变获取typeid

            if (in_array($type, $dataType)) {
                $data[$type][] = $v;
            } else {
                $dataType[] = $type;
                $data[$type][] = $v;
            }
        }

        return $data;
    }

    /*
     * 将购物车中的商品类型和信息转化为商品详细的数组
     */
    public function changeCartordertoGoodsarr($customer = null, $order_type = null)
    {
        if ($customer == null || $order_type == null) {
            throw new BadRequestHttpException('传入参数有空值不合要求');
            return;
        }
        $origintotalmoney = 0;
        $coursemoney = 0;
        $scholarshipoffset = 0;
        $totalcostcashmoney = 0;
        $mechanicmode = Fun::getSiteMode();
        $mechanic = [];
        $goodsarr = [];
        $deposit_need = 0;
        $full_course = [];
        $isBuy = [];
        $isMaxBuy = [];
        $isNum = [];
        $is_showaddress = false;//是否需要用户地址的显示和提交
        $onlycoursegood = true;
        $hasclassmanage = true;//课程商品是否拥有对应的排课管理记录，没有的话提示商品错误不要让用户支付
        if (!empty($order_type) && count($order_type) > 0) {
            $cart = new CartManage();
            /*#147 奖学金的存储在新表customer_branchaccount中了，所以从此处获取*/
            $availablesholarshi = $customer['scholarship_available'] ? $customer['scholarship_available'] : 0;//会员用户可用的奖学金金额

            foreach ($order_type as $type => $cartids) {
                foreach ($cartids as $v) {
                    $goodcart = $cart->getOneCartforone($v);
                    $goodid = $goodcart['goods_id'];
                    $good_group = GoodsGroup::find()->where(['goods_id'])->asArray()->all();
                    foreach ($good_group as $key => $val) {

                    }
                    $goodobj = Goods::findOne($goodid);
                    if (!empty($goodobj)) {
                        $good = $goodobj->toArray();
                        $good['quantity'] = $goodcart['quantity'];
                        $good['totalmoney'] = $goodcart['quantity'] * $good['price'];
                        $origintotalmoney += $good['totalmoney'];
                        $deposit_need += $good['deposit'];
                        if ($good['type_id'] == 1) {
                            $coursemoney += $good['totalmoney'];
                            //如果是课程类型的话查该排课的满额人数是否有满额的
                            $goods_attr = GoodsAttr::find()->where(['goods_id' => $good['id'], 'obj_type' => 'max_number'])->one();
                            $max_number = $goods_attr ? $goods_attr['value'] : 0;
                            $numstatus = $this->getNumStatus($good['id'], $max_number, $good['quantity']);
                            if ($numstatus['status'] == 'full') {
                                $full_course[] = $good['name'] . '(' . $numstatus['num'] . ')';//获取满额的课程数组
                            }
                        }
                        if ($type != 1) {
                            $is_showaddress = true;//如果不是课程商品，那么地址就要显示
                            $onlycoursegood = false;
                        }
                        if (isset($goodobj->mechanic)) {
                            $mechanic = $goodobj->mechanic;
                            $good['mechanic_id'] = $mechanic->id;
                        }
                        if (!empty($good['type_id'])) {
                            $goodsarr[$good['type_id']][] = $good;
                        } else {
                            $goodsarr[0][] = $good;
                        }
                        //数量是否符合要求的判断，未测试
                        $param = [];
                        $param['goods_id'] = $good['id'];
                        $param['quantity'] = $good['quantity'];
                        if (!$cart->validateIsBuy($good['id'])) {
                            $isBuy[] = $good['id'];
                        }
                        if (!$cart->validateMaxBuy($param)) {//这种验证好像不好使，后期测测再修改
                            $isMaxBuy[] = $good['id'];
                        }
                        if (!$cart->validateNum($param)) {
                            $isNum[] = $good['id'];
                        }
                    }
                }
            }
            /*不属于同一计划内的商品，在同一购物车内不能同时存在*/

            if ($availablesholarshi >= $coursemoney) {
                $scholarshipoffset = $coursemoney;
            } else {
                //奖学金不够付课程费用
                $scholarshipoffset = $availablesholarshi;
            }
            $totalcostcashmoney = $origintotalmoney - $scholarshipoffset;
            if (!empty($goodsarr)) {
                foreach ($goodsarr as $k => $gooda) {
                    foreach ($gooda as $key => $g) {
                        if ($g['type_id'] == 1) {
                            $g['scholarship_money'] = sprintf("%.2f", $scholarshipoffset * ($g['totalmoney'] / $coursemoney));
                        } else {
                            $g['scholarship_money'] = 0;
                        }
                        $goodsarr[$k][$key] = $g;

                        $classmanage = null;
                        $classmanage = ClassManage::findOne(['is_old' => 0, 'associate_id' => $g['id']]);
                        if (empty($classmanage)) {
                            $hasclassmanage = false;
                            break 2;
                        }
                    }
                }
            }
            $data['origintotalmoney'] = $origintotalmoney;
            $data['scholarshipoffset'] = $scholarshipoffset;
            $data['totalcostcashmoney'] = $totalcostcashmoney;
            $data['mechanicmode'] = $mechanicmode;
            $data['is_showaddress'] = $is_showaddress;
            $data['coursemoney'] = $coursemoney;
            $data['onlycoursegood'] = $onlycoursegood;
            $data['isBuy'] = $isBuy;//是否可购买
            $data['isMaxBuy'] = $isMaxBuy;//是否超最大购买数量
            $data['isNum'] = $isNum;//商品数量是否大于库存
            $data['full_course'] = $full_course;
            $data['goodsarr'] = $goodsarr;
            $data['deposit_need'] = $deposit_need;
            $data['hasclassmanage'] = $hasclassmanage;
            return $data;
        } else {
            //错误提示
            \Yii::$app->session->setFlash('fail', '购物车为空');
            return \Yii::$app->response->redirect(Fun::url(['checkout/index']));
        }

    }


    public function changeSquareCartordertoGoodsarr($customer = null, $order_type = null)
    {
        if ($customer == null || $order_type == null) {
            throw new BadRequestHttpException('传入参数有空值不合要求');
            return;
        }
        $origintotalmoney = 0;
        $coursemoney = 0;
        $scholarshipoffset = 0;
        $totalcostcashmoney = 0;
        $mechanicmode = Fun::getSiteMode();
        $mechanic = [];
        $goodsarr = [];
        $deposit_need = 0;
        $full_course = [];
        $isBuy = [];
        $isMaxBuy = [];
        $isNum = [];
        $is_showaddress = false;//是否需要用户地址的显示和提交
        $onlycoursegood = true;
        $hasclassmanage = true;//课程商品是否拥有对应的排课管理记录，没有的话提示商品错误不要让用户支付
        if (!empty($order_type) && count($order_type) > 0) {
            $cart = new CartManage();
            /*#147 奖学金的存储在新表customer_branchaccount中了，所以从此处获取*/
            $availablesholarshi = $customer['scholarship_available'] ? $customer['scholarship_available'] : 0;//会员用户可用的奖学金金额

            foreach ($order_type as $type => $cartids) {
                foreach ($cartids as $v) {
                    $goodcart = $cart->getOneCartforone($v);
                    $goodid = $goodcart['goods_id'];
                    $good_group = GoodsGroup::find()->where(['goods_id' => $goodid])->asArray()->all();
                    $goodobj = Goods::findOne($goodid);
                    if (!empty($goodobj)) {
                        $good = $goodobj->toArray();
                        $good['quantity'] = $goodcart['quantity'];
                        $good['totalmoney'] = $goodcart['quantity'] * $good['price'];
                        $origintotalmoney += $good['totalmoney'];
                        $deposit_need += $good['deposit'];
                        $goods_attr = GoodsAttr::find()->where(['goods_id' => $good['id']])->indexBy('obj_type')->asArray()->all();
                        if ($good['type_id'] == 1) {
                            $coursemoney += $good['totalmoney'];
                            //如果是课程类型的话查该排课的满额人数是否有满额的

                            $max_number = isset($goods_attr['max_number']) ? $goods_attr['max_number']['value'] : 0;
                            $numstatus = $this->getNumStatus($good['id'], $max_number, $good['quantity']);
                            if ($numstatus['status'] == 'full') {
                                $full_course[] = $good['name'] . '(' . $numstatus['num'] . ')';//获取满额的课程数组
                            }
                        }
                        if ($type != 1) {
                            $is_showaddress = true;//如果不是课程商品，那么地址就要显示
                            $onlycoursegood = false;
                        }
                        $teacher_data='';
                        if(isset($goods_attr['teacher'])){
                            $good['teacher_id'] = $goods_attr['teacher']['attribute_id'];
                        }
                        if (isset($goodobj->mechanic)) {
                            $mechanic = $goodobj->mechanic;
                            $good['mechanic_id'] = $mechanic->id;
                            $good['mechanic_area']=$mechanic->region;
                        }
                        if (!empty($good['type_id'])) {
                            $goodsarr[$good['type_id']][] = $good;
                        } else {
                            $goodsarr[0][] = $good;
                        }
                        //数量是否符合要求的判断，未测试
                        $param = [];
                        $param['goods_id'] = $good['id'];
                        $param['quantity'] = $good['quantity'];
                        if (!$cart->validateIsBuy($good['id'])) {
                            $isBuy[] = $good['id'];
                        }
                        if (!$cart->validateMaxBuy($param)) {//这种验证好像不好使，后期测测再修改
                            $isMaxBuy[] = $good['id'];
                        }
                        if (!$cart->validateNum($param)) {
                            $isNum[] = $good['id'];
                        }
                    }
                }
            }
            /*不属于同一计划内的商品，在同一购物车内不能同时存在*/

            if ($availablesholarshi >= $coursemoney) {
                $scholarshipoffset = $coursemoney;
            } else {
                //奖学金不够付课程费用
                $scholarshipoffset = $availablesholarshi;
            }
            $totalcostcashmoney = $origintotalmoney - $scholarshipoffset;
            /*if(!empty($goodsarr)){
                var_dump($goodsarr);exit();
                    foreach ($gooda as $key => $g) {
                        if ($g['type_id'] == 1) {
                            $g['scholarship_money'] = sprintf("%.2f", $scholarshipoffset * ($g['totalmoney'] / $coursemoney));
                        } else {
                            $g['scholarship_money'] = 0;
                        }
                        $goodsarr[$k][$key] = $g;

                        $classmanage = null;
                        $classmanage = ClassManage::findOne(['is_old'=>0,'associate_id'=>$g['id']]);
                        if(empty($classmanage)){
                            $hasclassmanage = false;
                            break 2;
                        }
                    }
                }
            }*/
            $data['origintotalmoney'] = $origintotalmoney;
            $data['scholarshipoffset'] = $scholarshipoffset;
            $data['totalcostcashmoney'] = $totalcostcashmoney;
            $data['mechanicmode'] = $mechanicmode;
            $data['is_showaddress'] = $is_showaddress;
            $data['coursemoney'] = $coursemoney;
            $data['onlycoursegood'] = $onlycoursegood;
            $data['isBuy'] = $isBuy;//是否可购买
            $data['isMaxBuy'] = $isMaxBuy;//是否超最大购买数量
            $data['isNum'] = $isNum;//商品数量是否大于库存
            $data['full_course'] = $full_course;
            $data['goodsarr'] = $goodsarr;
            $data['deposit_need'] = $deposit_need;
            $data['hasclassmanage'] = $hasclassmanage;
            return $data;
        } else {
            //错误提示
            \Yii::$app->session->setFlash('fail', '购物车为空');
            return \Yii::$app->response->redirect(Fun::url(['checkout/index']));
        }

    }


    /*
     * 判断课程满额人数是否超支
     */
    protected function getNumStatus($goods_id, $max_number, $quantity)
    {
        /*
     * 获取交了保证金的用户ids
         * 上面一行是之前的需求，现在是只要订单付款了，那就算得上是有效的可以上课的，
         * 所以不能根据保证金交了来计算判断满额人数，要根据交钱的订单
     */
        /*$customerids_arr = (new Query())->select('id')->from('{{%customer}}')->where(['>','deposit',0])->all(Fun::getSysDb());
        $customerids = [];
        if(!empty($customerids_arr)){
            foreach($customerids_arr as $customerid){
                $customerids[] = $customerid['id'];
            }
        }
     */
        $num = 0;
        //获取交了保证金的用户的订单当中的该商品购买量，不能从订单里面找，得从order_items里面找，这里是对应到商品的
        $currentcourseorders = (new Query())->select('orderitems.nums')->from('{{%orders}}')->leftJoin(['orderitems' => '{{%orders_items}}'], '{{%orders}}.id = orderitems.orders_id')->where(['{{%orders}}.is_delete' => 0, '{{%orders}}.pay_status' => 1, 'orderitems.goods_id' => $goods_id])->all(Fun::getSiteDb());
        if (!empty($currentcourseorders)) {
            foreach ($currentcourseorders as $currentcourse) {
                $num += $currentcourse['nums'];
            }
        }
        $numstr = $num + $quantity . '/' . $max_number . '已有数目:' . $num;
        $status = (($num + $quantity) > $max_number) ? 'full' : 'notfull';
        return [
            'num' => $numstr,
            'status' => $status
        ];
    }

    /**
     * 提交订单
     *
     */
    public function onSuccess()
    {

    }

    /*
     * 添加studentcheck记录,现在逻辑改为下单就交保证金，不过有的现金足够了不用交保证金，所以这里的pay_deposit实际没啥判断效用
     */
    public function addStudentCheck($pay_deposit = false, $classmanage_id = null, $order_id, $class_student_id, $student_id)
    {
        if (empty($classmanage_id)) {
            return false;
        }
        $classmanage = ClassManage::findOne($classmanage_id);
        if (empty($classmanage)) {
            return false;
        }
        $openclass_status = $classmanage->status;
        if ($openclass_status == 1) {//如果已经开班了
            $studentcheck_num = StudentCheck::find()->where(['class_student_id' => $class_student_id, 'order_sales_id' => $order_id, 'student_id' => $student_id])->max('class_lesson_id');
            $class_lesson_maxnum = ClassLesson::find()->where(['class_id' => $classmanage_id])->max("lesson_id");
            $class_lesson_minnum = ClassLesson::find()->where(['class_id' => $classmanage_id])->min("lesson_id");//当没有classlesson的时候，最大最小值都为空,有没有一种不正常的可能，就是classlesson不是按照顺序排的,现在是，以后变了需求再说
            $studentchecks = [];
            $lessonstudents = [];
            $total_count = ClassLesson::find()->where(['class_id' => $classmanage_id])->max("lesson");
            if (empty($class_lesson_maxnum)) {
                $class_lesson_maxnum = 0;
            }
            if (empty($class_lesson_minnum)) {
                $class_lesson_minnum = 0;
            }
            if (empty($studentcheck_num)) {//在student_check里面还没有该学生的记录
                $studentcheck_num = $class_lesson_minnum - 1;
            }
            //只要开班了，不管交没交保证金将所有课时的记录全都放到student_check和lesson_student表当中
            if ($studentcheck_num < $class_lesson_maxnum) {
                for ($i = 1; $i <= $total_count; $i++) {
                    $student_check['class_student_id'] = $class_student_id;
                    $student_check['order_sales_id'] = $order_id;
                    $student_check['student_id'] = $student_id;
                    $class_lesson = ClassLesson::findOne(['class_id' => $classmanage_id, 'lesson' => $i]);
                    //如果已经存在了就不可以再插入了
                    $ori_studentc = StudentCheck::findOne(['class_student_id' => $class_student_id, 'order_sales_id' => $order_id, 'student_id' => $student_id, 'class_lesson_id' => $class_lesson['lesson_id']]);
                    if (empty($ori_studentc)) {
                        $student_check['class_lesson_id'] = $class_lesson['lesson_id'];
                        if (time() > $class_lesson['class_date']) {
                            //当前时间大于课程的开课时间了，所以就更改状态为请假状态
                            $student_check['status'] = 2;//状态为请假状态
                        } else {
                            $student_check['status'] = 0;
                        }
                        $studentchecks[] = $student_check;
                    }
                    $ori_lesson_student = LessonStudent::findOne(['student_id' => $student_id, 'lesson_id' => $class_lesson['lesson_id']]);
                    if (empty($ori_lesson_student)) {
                        $lesson_student['lesson_id'] = $class_lesson['lesson_id'];
                        $lesson_student['student_id'] = $student_id;
                        if (time() > $class_lesson['class_date']) {
                            //当前时间大于课程的开课时间了，所以就更改状态为请假状态
                            $lesson_student['status'] = 2;//状态为请假状态
                        } else {
                            $lesson_student['status'] = 0;
                        }
                        $lessonstudents[] = $lesson_student;
                    }
                }
                if (!empty($studentchecks)) {
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', [
                        'class_student_id', 'order_sales_id', 'student_id', 'class_lesson_id', 'status'
                    ], $studentchecks)->execute();
                }
                if (!empty($lessonstudents)) {
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', [
                        'lesson_id', 'student_id', 'status'
                    ], $lessonstudents)->execute();
                }
            }
        }
        return true;
    }

    public function fillCustomerModel($customerModel, $openid, $attributes, $cardnumber)
    {
        if (empty($customerModel->gttopenid)) {
            $customerModel->gttopenid = $openid;
        }
        //修改将之前的函数参数由原来的gttopenid改为通用的openid并增加判断综合体openid
        if (empty($customerModel->zhtopenid)) {
            $customerModel->zhtopenid = $openid;
        }
        if (empty($customerModel->nick_name)) {
            $customerModel->nick_name = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
        }
        if (empty($customerModel->name)) {
            $customerModel->name = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
        }
        if (empty($customerModel->sex)) {
            $sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
            $customerModel->sex = $sex;
        }
        if (empty($customerModel->logo)) {
            $customerModel->logo = $attributes['headimgurl'];
        }
        /*if (empty($customerModel->card_id)) {
            $customerModel->card_id = $cardnumber;
        }
        if (empty($customerModel->card_qrcode)) {
            $customerModel->card_qrcode = md5($cardnumber);
        }*/
        if (empty($customerModel->province)) {
            $customerModel->province = isset($attributes['province']) ? $attributes['province'] : '';
        }
        if (empty($customerModel->city)) {
            $customerModel->city = isset($attributes['city']) ? $attributes['city'] : '';
        }
        return $customerModel;
    }

    /*
     * 微信注册功能-共同体
     */
    public function doWechatCustomerRegister($attributes, $model, $websiteId, $mode = null)
    {
        $site_id = $model->site_id ? $model->site_id : 0;
        $mode = empty($mode) ? 1 : $mode;//mode改为传参不写死
        $clientid = \Yii::$app->session->get("wechat_authclientid") ? \Yii::$app->session->get("wechat_authclientid") : 0;
        $telephone = $model->telephone;
        if ($site_id == 9) {//针对以往泰安旧数据的操作
            $old_customer = Customer::find()->where(['mobile' => $telephone])->andWhere(['like', 'gttopenid', '023%', false])->one();
            if (!empty($old_customer)) {
                $old_customer->gttopenid = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];
                $old_customer->save(false);
                $old_loginauth = LoginAuth::findOne(['user_id' => $old_customer->id, 'web_site_id' => '23']);
                if (!empty($old_loginauth)) {
                    $old_loginauth->mode = 1;
                    $old_loginauth->source_id = $attributes['openid'];
                    $old_loginauth->web_site_id = $websiteId;
                    $old_loginauth->save(false);
                }
            }
        }
        $auth = LoginAuth::find()->where(['source_id' => $attributes['openid'], 'mode' => $mode])->one();
        //未登录的
        $borned_year = isset($model->age) && !empty($model->age) && ($model->age != 'default') ? $model->age : null;
        $student_name = isset($model->name) && !empty($model->name) ? $model->name : null;
        $customer_fortel = Customer::find()->where(['mobile' => $telephone])->one();//如果已经存在这个手机号的用户了
        $gttopenid = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];
        if (!empty($customer_fortel)) {//不可与已有用户手机号码重复
            if (!empty($customer_fortel['gttopenid'])) {
                if ($customer_fortel['gttopenid'] != $gttopenid) {
                    return 'fail_a';
                }
            }
        }

        /*
        * 要保证同一公众号用户多次注册登录的错误不存在，还要保证之前更改用户手机号的正确性
        * 一开始的时候就要进行判断，先查一下当前openid是否已经有记录了，没有则正常进行下去；
        * 如果有了，那就获取当前输入的手机号，是否是一条记录，和openid对应的用户记录是否是一条，不是的话那就要提示错误，一个公众号不可以对应于多条记录*/
        $cus = Customer::findOne(['gttopenid' => $gttopenid]);
        if (!empty($cus)) {
            $cus_inputtel = Customer::findOne(['mobile' => $telephone]);
            if ($cus_inputtel->id != $cus->id) {
                return 'fail_b';
            }
        }
        //当前openid已经存在于数据库表中了，那么就不能再进行什么注册了
        $issuser_info = IsuserInfo::find()->where(['mobile' => $telephone, 'site_id' => $site_id])->one();//获取属于某个分店的发卡人

        //随机生成卡号
        $cardnumber = Createcard::GenerateCard();
        /**
         * 先理一下各种情况哈：
         * 1. 本身的customer表就是空的，直接所有字段都加进去；
         * 2. customer有手机号的记录了，但是gttopenid是空的，将gttopenid给赋值，至于card_id和code要根据是否为空来添加；
         */
        if ($auth !== null) {
            $gttopenid = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];//获取当前session中访问用户的二维码
            //授权登录表里面有记录
            $user = $auth->user;
            if (empty($user)) {
                $customerMod = Customer::findOne(['mobile' => $telephone]);
                if (!empty($customerMod)) {
                    $customerModel = $this->fillCustomerModel($customerMod, $gttopenid, $attributes, $cardnumber);
                    if ($customerModel->save(false)) {
                        if (!empty($issuser_info)) {
                            $issuser_info->customer_id = $customerModel->id;
                            $issuser_info->save(false);
                            $customerModel->is_sender = 1;
                            $customerModel->save(false);
                        }
                        $auth->user_id = $customerModel->id;
                        if ($auth->save(false)) {
                            \Yii::$app->user->login($customerModel);
                            \Yii::$app->session->setFlash('success', '微信登录成功');
                        }
                    }
                } else {//如果不存在这个手机号的对应用户
                    $customerModel = Customer::findOne(['gttopenid' => $gttopenid]);
                    if (!empty($customerModel)) {
                        $customerModel->mobile = $telephone;
                        if ($customerModel->save(false)) {
                            if (!empty($issuser_info)) {
                                $issuser_info->customer_id = $customerModel->id;
                                $issuser_info->save(false);
                                $customerModel->is_sender = 1;
                                $customerModel->save(false);
                            }
                            $auth->user_id = $customerModel->id;
                            if ($auth->save(false)) {
                                \Yii::$app->user->login($customerModel);
                                \Yii::$app->session->setFlash('success', '微信登录成功');
                            }
                        }
                    } else {//不管是手机号还是openid都没有找到对应的记录
                        $sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
                        $user = new \common\models\datas\Customer([
                            'nick_name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                            'name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                            'sex' => $sex,
                            'source' => 1,
                            'logo' => $attributes['headimgurl'],
                            'gttopenid' => $gttopenid,
                            'mobile' => $telephone,
                            //无什么卵用了以后就'site_id' => $site_id,
                            'card_id' => $cardnumber,
                            'card_qrcode' => md5($cardnumber),
                            'province' => isset($attributes['province']) ? $attributes['province'] : '',
                            'city' => isset($attributes['city']) ? $attributes['city'] : ''
                        ]);
                        if ($user->save(false)) {
                            $auth->user_id = $user->id;
                            if (!empty($issuser_info)) {
                                $issuser_info->customer_id = $user->id;
                                $issuser_info->save(false);
                                $user->is_sender = 1;
                                $user->save(false);
                            }
                            if ($auth->save(false)) {
                                \Yii::$app->user->login($user);
                                \Yii::$app->session->setFlash('success', '微信登录成功');
                            }
                        }
                    }
                }
            } else {
                $user->mobile = $telephone;
                $user->gttopenid = $gttopenid;
                if ($user->save(false)) {//如果对应的user不为空，那么久更新user
                    if (!empty($issuser_info)) {
                        $issuser_info->customer_id = $user->id;
                        $issuser_info->save(false);
                        $user->is_sender = 1;
                        $user->save(false);
                    }
                    \Yii::$app->user->login($user);
                    \Yii::$app->session->setFlash('success', '微信登录成功');
                }
            }
        } else {
            $sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
            $gttopenid = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];
            $customerMod = Customer::findOne(['mobile' => $telephone]);
            if (!empty($customerMod)) {
                $customerModel = $this->fillCustomerModel($customerMod, $gttopenid, $attributes, $cardnumber);
                if (!empty($issuser_info)) {
                    $issuser_info->customer_id = $customerModel->id;
                    $issuser_info->save(false);
                    $customerModel->is_sender = 1;
                }
                if ($customerModel->save(false)) {
                    $auth = new LoginAuth([
                        'user_id' => $customerModel->id,
                        'source' => $clientid,
                        'source_id' => $attributes['openid'],
                        'web_site_id' => $websiteId,
                        'mode' => $mode
                    ]);
                    if ($auth->save(false)) {
                        \Yii::$app->user->login($customerModel);
                        \Yii::$app->session->setFlash('success', '微信登录成功');
                    }
                }
            } else {
                $customerModel = Customer::findOne(['gttopenid' => $gttopenid]);
                if (!empty($customerModel)) {
                    $customerModel->mobile = $telephone;
                    if (!empty($issuser_info)) {
                        $issuser_info->customer_id = $customerModel->id;
                        $issuser_info->save(false);
                        $customerModel->is_sender = 1;
                    }
                    if ($customerModel->save(false)) {
                        $auth = new LoginAuth([
                            'user_id' => $customerModel->id,
                            'source' => $clientid,
                            'source_id' => $attributes['openid'],
                            'web_site_id' => $websiteId,
                            'mode' => $mode
                        ]);
                        if ($auth->save(false)) {
                            \Yii::$app->user->login($customerModel);
                            \Yii::$app->session->setFlash('success', '微信登录成功');
                        }
                    }
                } else {//不管是手机号还是openid都没有找到对应的记录
                    $user = new \common\models\datas\Customer([
                        'nick_name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                        'name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                        'site_id' => $site_id,
                        'sex' => $sex,
                        'source' => 1,
                        'logo' => $attributes['headimgurl'],
                        'gttopenid' => $gttopenid,
                        'mobile' => $telephone,
                        'card_id' => $cardnumber,
                        'card_qrcode' => md5($cardnumber),
                        'province' => isset($attributes['province']) ? $attributes['province'] : '',
                        'city' => isset($attributes['city']) ? $attributes['city'] : ''
                    ]);
                    if ($user->save(false)) {
                        if (!empty($issuser_info)) {
                            $issuser_info->customer_id = $user->id;
                            $issuser_info->save(false);
                            $user->is_sender = 1;
                            $user->save(false);
                        }
                        $auth = new LoginAuth([
                            'user_id' => $user->id,
                            'source' => $clientid,
                            'source_id' => $attributes['openid'],
                            'web_site_id' => $websiteId,
                            'mode' => $mode
                        ]);
                        if ($auth->save(false)) {
                            \Yii::$app->user->login($user);//更改两个表再绑定手机号注册的时候
                            \Yii::$app->session->setFlash('success', '微信登录成功');
                        }
                    }
                }
            }
        }
        $user_id = \Yii::$app->user->id;
        $student = Student::findOne(['customer_id' => $user_id]);
        if (empty($student)) {//注册的时候如果没有对应的学员自动加上对应的学员
            $student = new Student();
            $student->customer_id = $user_id;
            $student->created_at = time();
            $student->updated_at = time();
            $student->site_id = $site_id;
            $student->is_old = 0;
            if (!empty($borned_year)) {
                $student->age = $borned_year;
            }
            $student->name = !empty($student_name) ? $student_name : preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
            $student->nickname = !empty($student_name) ? $student_name : preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
            $student->sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
            $student->save(false);
        } else {
            if (!empty($borned_year)) {
                $student->age = $borned_year;
            }
            if (!empty($student_name)) {
                $student->name = $student_name;;
                $student->nickname = $student_name;
            }
            $student->save(false);
        }
        /*更改学员的年龄字段*/
        //\Yii::error('app user id' . \Yii::$app->user->id);
        return \Yii::$app->user->id;//返回当前登录用户
    }

    /*
     * 微信注册功能-综合体
     */
    public function doWechatzhtCustomerRegister($attributes, $model, $websiteId, $mode = null)
    {
        $site_id = isset($model->site_id)&&$model->site_id!=0 ? $model->site_id : 2;
        $mode = empty($mode) ? 1 : $mode;//mode改为传参不写死
        $clientid = \Yii::$app->session->get("wechat_authclientid") ? \Yii::$app->session->get("wechat_authclientid") : 0;
        $telephone = $model->telephone;
        $auth = LoginAuth::find()->where(['source_id' => $attributes['openid'], 'mode' => 2])->one();
        //未登录的
        $borned_year = isset($model->age) && !empty($model->age) && ($model->age != 'default') ? $model->age : null;
        $student_name = isset($model->name) && !empty($model->name) ? $model->name : null;
        $customer_fortel = Customer::find()->where(['mobile' => $telephone])->one();//如果已经存在这个手机号的用户了
        $zhtopenid = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];
        if (!empty($customer_fortel)) {//不可与已有用户手机号码重复
            if (!empty($customer_fortel['zhtopenid'])) {
                if ($customer_fortel['zhtopenid'] != $zhtopenid) {
                    return 'fail_a';
                }
            }
        }

        /*
        * 要保证同一公众号用户多次注册登录的错误不存在，还要保证之前更改用户手机号的正确性
        * 一开始的时候就要进行判断，先查一下当前openid是否已经有记录了，没有则正常进行下去；
        * 如果有了，那就获取当前输入的手机号，是否是一条记录，和openid对应的用户记录是否是一条，不是的话那就要提示错误，一个公众号不可以对应于多条记录*/
        $cus = Customer::findOne(['zhtopenid' => $zhtopenid]);
        if (!empty($cus)) {
            $cus_inputtel = Customer::findOne(['mobile' => $telephone]);
            if ($cus_inputtel->id != $cus->id) {
                return 'fail_b';
            }
        }
        //当前openid已经存在于数据库表中了，那么就不能再进行什么注册了
        $issuser_info = IsuserInfo::find()->where(['mobile' => $telephone, 'site_id' => $site_id])->one();//获取属于某个分店的发卡人

        //随机生成卡号
        $cardnumber = Createcard::GenerateCard();
        /**
         * 先理一下各种情况哈：
         * 1. 本身的customer表就是空的，直接所有字段都加进去；
         * 2. customer有手机号的记录了，但是zhtopenid是空的，将zhtopenid给赋值，至于card_id和code要根据是否为空来添加；
         */

        if ($auth !== null) {
            $zhtopenid = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];//获取当前session中访问用户的二维码
            //授权登录表里面有记录
            $user = $auth->user;
            if (empty($user)) {
                $customerMod = Customer::findOne(['mobile' => $telephone]);
                if (!empty($customerMod)) {
                    $customerModel = $this->fillCustomerModel($customerMod, $zhtopenid, $attributes, $cardnumber);
                    if ($customerModel->save(false)) {
                        if (!empty($issuser_info)) {
                            $issuser_info->customer_id = $customerModel->id;
                            $issuser_info->save(false);
                            $customerModel->is_sender = 1;
                            $customerModel->save(false);
                        }
                        $auth->user_id = $customerModel->id;
                        if ($auth->save(false)) {
                            \Yii::$app->user->login($customerModel);
                            \Yii::$app->session->setFlash('success', '微信登录成功');
                        }
                    }
                } else {//如果不存在这个手机号的对应用户
                    $customerModel = Customer::findOne(['zhtopenid' => $zhtopenid]);
                    if (!empty($customerModel)) {
                        $customerModel->mobile = $telephone;
                        if ($customerModel->save(false)) {
                            if (!empty($issuser_info)) {
                                $issuser_info->customer_id = $customerModel->id;
                                $issuser_info->save(false);
                                $customerModel->is_sender = 1;
                                $customerModel->save(false);
                            }
                            $auth->user_id = $customerModel->id;
                            if ($auth->save(false)) {
                                $this->saveCustomerBranchAccount($customerModel->id);
                                \Yii::$app->user->login($customerModel);
                                \Yii::$app->session->setFlash('success', '微信登录成功');
                            }
                        }
                    } else {//不管是手机号还是openid都没有找到对应的记录
                        $sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
                        $user = new \common\models\datas\Customer([
                            'nick_name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                            'name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                            'sex' => $sex,
                            'source' => 1,
                            'logo' => $attributes['headimgurl'],
                            'zhtopenid' => $zhtopenid,
                            'mobile' => $telephone,
                            //无什么卵用了以后就
                            'site_id' => $site_id,
                            'card_id' => 't'.rand(pow(10,8), pow(10,9)-1),
                            //'card_qrcode' => md5($cardnumber),
                            'province' => isset($attributes['province']) ? $attributes['province'] : '',
                            'city' => isset($attributes['city']) ? $attributes['city'] : ''
                        ]);
                        if ($user->save(false)) {
                            $auth->user_id = $user->id;
                            if (!empty($issuser_info)) {
                                $issuser_info->customer_id = $user->id;
                                $issuser_info->save(false);
                                $user->is_sender = 1;
                                $user->save(false);
                            }
                            $this->saveCustomerBranchAccount($user->id);
                            if ($auth->save(false)) {
                                \Yii::$app->user->login($user);
                                \Yii::$app->session->setFlash('success', '微信登录成功');
                            }
                        }
                    }
                }
            } else {
                $user->mobile = $telephone;
                $user->zhtopenid = $zhtopenid;
                if ($user->save(false)) {//如果对应的user不为空，那么久更新user
                    if (!empty($issuser_info)) {
                        $issuser_info->customer_id = $user->id;
                        $issuser_info->save(false);
                        $user->is_sender = 1;
                        $user->save(false);
                    }
                    $this->saveCustomerBranchAccount($user->id);
                    \Yii::$app->user->login($user);
                    \Yii::$app->session->setFlash('success', '微信登录成功');
                }
            }
        } else {
            $sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
            $zhtopenid = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];
            $customerMod = Customer::findOne(['mobile' => $telephone]);
            if (!empty($customerMod)) {
                $customerModel = $this->fillCustomerModel($customerMod, $zhtopenid, $attributes, $cardnumber);
                if (!empty($issuser_info)) {
                    $issuser_info->customer_id = $customerModel->id;
                    $issuser_info->save(false);
                    $customerModel->is_sender = 1;
                }
                if ($customerModel->save(false)) {
                    $auth = new LoginAuth([
                        'user_id' => $customerModel->id,
                        'source' => $clientid,
                        'source_id' => $attributes['openid'],
                        'web_site_id' => $websiteId,
                        'mode' => $mode
                    ]);
                    $this->saveCustomerBranchAccount($customerModel->id);
                    if ($auth->save(false)) {
                        \Yii::$app->user->login($customerModel);
                        \Yii::$app->session->setFlash('success', '微信登录成功');
                    }
                }
            } else {
                $customerModel = Customer::findOne(['zhtopenid' => $zhtopenid]);
                if (!empty($customerModel)) {
                    $customerModel->mobile = $telephone;
                    if (!empty($issuser_info)) {
                        $issuser_info->customer_id = $customerModel->id;
                        $issuser_info->save(false);
                        $customerModel->is_sender = 1;
                    }
                    if ($customerModel->save(false)) {
                        $auth = new LoginAuth([
                            'user_id' => $customerModel->id,
                            'source' => $clientid,
                            'source_id' => $attributes['openid'],
                            'web_site_id' => $websiteId,
                            'mode' => $mode
                        ]);
                        $this->saveCustomerBranchAccount($customerModel->id);
                        if ($auth->save(false)) {
                            \Yii::$app->user->login($customerModel);
                            \Yii::$app->session->setFlash('success', '微信登录成功');
                        }
                    }
                } else {//不管是手机号还是openid都没有找到对应的记录
                    $user = new \common\models\datas\Customer([
                        'nick_name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                        'name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                        'site_id' => $site_id,
                        'sex' => $sex,
                        'source' => 1,
                        'logo' => $attributes['headimgurl'],
                        'zhtopenid' => $zhtopenid,
                        'mobile' => $telephone,
                        'card_id' => 't'.rand(pow(10,8), pow(10,9)-1),
                        //'card_qrcode' => md5($cardnumber),
                        'province' => isset($attributes['province']) ? $attributes['province'] : '',
                        'city' => isset($attributes['city']) ? $attributes['city'] : ''
                    ]);
                    if ($user->save(false)) {
                        if (!empty($issuser_info)) {
                            $issuser_info->customer_id = $user->id;
                            $issuser_info->save(false);
                            $user->is_sender = 1;
                            $user->save(false);
                        }
                        $auth = new LoginAuth([
                            'user_id' => $user->id,
                            'source' => $clientid,
                            'source_id' => $attributes['openid'],
                            'web_site_id' => $websiteId,
                            'mode' => $mode
                        ]);
                        $this->saveCustomerBranchAccount($user->id);
                        if ($auth->save(false)) {
                            \Yii::$app->user->login($user);//更改两个表再绑定手机号注册的时候
                            \Yii::$app->session->setFlash('success', '微信登录成功');
                        }
                    }
                }
            }
        }
        $user_id = \Yii::$app->user->id;
        $student = Student::findOne(['customer_id' => $user_id]);
        if (empty($student)) {//注册的时候如果没有对应的学员自动加上对应的学员
            $student = new Student();
            $student->customer_id = $user_id;
            $student->created_at = time();
            $student->updated_at = time();
            $student->site_id = $site_id;
            $student->is_old = 0;
            if (!empty($borned_year)) {
                $student->age = $borned_year;
            }
           // $student->name = !empty($student_name) ? $student_name : preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
            $student->nickname = !empty($student_name) ? $student_name : preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
            $student->sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
            $student->save(false);
        } else {
            if (!empty($borned_year)) {
                $student->age = $borned_year;
            }
            if (!empty($student_name)) {
                $student->name = $student_name;;
                $student->nickname = $student_name;
            }
            $student->save(false);
        }
        /*更改学员的年龄字段*/
        //\Yii::error('app user id' . \Yii::$app->user->id);
        return \Yii::$app->user->id;//返回当前登录用户
    }

    public function saveCustomerBranchAccount($customer_id){
        $customerBranchAccount=CustomerBranchaccount::find()->where(['customer_id'=>$customer_id,'site_id'=>Fun::getSiteId()])->one();
        if(empty($customerBranchAccount)){
            $model=new CustomerBranchaccount();
            $model->customer_id=$customer_id;
            $model->site_id=Fun::getSiteId();
            $model->mode=2;
            $model->created_at=time();
            $model->grade_id=1;
            $model->pay_password=md5('123456');
            $model->save(false);
        }
    }

    public function doWechatCustomerRegisterfortaian($attributes, $model, $websiteId, $url)
    {
        $site_id = Fun::getSiteId() ? Fun::getSiteId() : 0;
        $clientid = \Yii::$app->session->get("wechat_authclientid") ? \Yii::$app->session->get("wechat_authclientid") : 0;
        $auth = LoginAuth::find()->where(['source_id' => $attributes['openid'], 'web_site_id' => $websiteId])->one();
        //未登录的
        $telephone = $model->telephone;
        $borned_year = isset($model->age) && !empty($model->age) && ($model->age != 'default') ? $model->age : null;
        $student_name = isset($model->name) && !empty($model->name) ? $model->name : null;
        $customer_fortel = Customer::find()->where(['mobile' => $telephone])->one();
        $qrcode = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];
        if (!empty($customer_fortel)) {//不可与已有用户手机号码重复
            if (!empty($customer_fortel['qrcode'])) {
                if ($customer_fortel['qrcode'] != $qrcode) {
                    \Yii::$app->session->setFlash('error', '该手机号已被其他微信用户绑定，请重新填写。');
                    return 0;
                }
            }
        }
        $issuser_info = IsuserInfo::find()->where(['mobile' => $telephone, 'site_id' => $site_id])->one();//获取属于某个分店的发卡人

        //随机生成卡号
        $cardnumber = Createcard::GenerateCard();
        if ($auth !== null) {
            $qrcode = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];//获取当前session中访问用户的二维码
            //授权登录表里面有记录
            $user = $auth->user;
            if (empty($user)) {//为空说明auth里面没有对应正确的user，所以auth要更新,什么情况下会出现auth记录存在，但是其对应的user是空的？就是手动删除数据库表user的时候没有删除表
                $customerModel = Customer::find()->where(['zhtopenid' => $qrcode])->one();
                if (!empty($customerModel)) {//customer表中有当前登录用户
                    //当前用户的手机号要绑定进去
                    $customerModel->mobile = $telephone;
                    if ($customerModel->save(false)) {
                        if (!empty($issuser_info)) {
                            $issuser_info->customer_id = $customerModel->id;
                            $issuser_info->save(false);
                            $customerModel->is_sender = 1;
                            $customerModel->save(false);
                        }
                        $auth->user_id = $customerModel->id;
                        if ($auth->save(false)) {
                            \Yii::$app->user->login($customerModel);
                            \Yii::$app->session->setFlash('success', '微信登录成功');
                        }
                    }
                } else {
                    $sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
                    $user = new \common\models\datas\Customer([
                        'nick_name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                        'name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']),
                        'sex' => $sex,
                        'source' => 1,
                        'logo' => $attributes['headimgurl'],
                        'qrcode' => $qrcode,
                        'mobile' => $telephone,
                        'site_id' => $site_id,
                        'card_id' => $cardnumber,
                        'card_qrcode' => md5($cardnumber),
                        'province' => isset($attributes['province']) ? $attributes['province'] : '',
                        'city' => isset($attributes['city']) ? $attributes['city'] : ''
                    ]);
                    if ($user->save(false)) {
                        $auth->user_id = $user->id;
                        if (!empty($issuser_info)) {
                            $issuser_info->customer_id = $user->id;
                            $issuser_info->save(false);
                            $user->is_sender = 1;
                            $user->save(false);
                        }
                        if ($auth->save(false)) {
                            \Yii::$app->user->login($user);
                            \Yii::$app->session->setFlash('success', '微信登录成功');
                        }
                    }
                }
            } else {
                $user->mobile = $telephone;
                $user->qrcode = $qrcode;
                if ($user->save(false)) {//如果对应的user不为空，那么久更新user
                    if (!empty($issuser_info)) {
                        $issuser_info->customer_id = $user->id;
                        $issuser_info->save(false);
                        $user->is_sender = 1;
                        $user->save(false);
                    }
                    \Yii::$app->user->login($user);
                    \Yii::$app->session->setFlash('success', '微信登录成功');
                }
            }
        } else {//用户未登录，而且auth表是空的没有记录
            $sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
            $qrcode = Util::zeroFill((string)$websiteId, '3') . $attributes['openid'];
            if (!empty($customer_fortel)) {//更新手机号要
                if (!empty($issuser_info)) {
                    $issuser_info->customer_id = $issuser_info->id;
                    $issuser_info->save(false);
                    $issuser_info->is_sender = 1;
                    $issuser_info->save(false);
                }
                $customer_fortel->qrcode = $qrcode;
                $customer_fortel->nick_name = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
                $customer_fortel->name = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
                $customer_fortel->sex = $sex;
                $customer_fortel->logo = $attributes['headimgurl'];
                $customer_fortel->card_id = $cardnumber;
                $customer_fortel->card_qrcode = md5($cardnumber);
                $customer_fortel->province = $cardnumber;
                $customer_fortel->city = isset($attributes['city']) ? $attributes['city'] : '';
                $customer_fortel->save(false);

                if ($issuser_info->save(false)) {
                    $auth = new LoginAuth([
                        'user_id' => $issuser_info->id,
                        'source' => $clientid,
                        'source_id' => $attributes['openid'],
                        'web_site_id' => $websiteId
                    ]);
                    if ($auth->save(false)) {
                        \Yii::$app->user->login($customer_fortel);
                        \Yii::$app->session->setFlash('success', '微信登录成功');
                    }
                }
            } else {
                \Yii::$app->session->setFlash('error', '对不起没有对应的微信用户');
            }
        }
        $user_id = \Yii::$app->user->id;
        $student = Student::findOne(['customer_id' => $user_id]);
        if (empty($student)) {//注册的时候如果没有对应的学员自动加上对应的学员
            $student = new Student();
            $student->customer_id = $user_id;
            $student->created_at = time();
            $student->updated_at = time();
            $student->site_id = Fun::getSiteId() ? Fun::getSiteId() : 0;
            $student->is_old = 0;
            if (!empty($borned_year)) {
                $student->age = $borned_year;
            }
            $student->name = !empty($student_name) ? $student_name : preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
            $student->nickname = !empty($student_name) ? $student_name : preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $attributes['nickname']);
            $student->sex = ($attributes['sex'] == 1) ? 'Male' : 'Female';
            $student->save(false);
        } else {
            if (!empty($borned_year)) {
                $student->age = $borned_year;
            }
            if (!empty($student_name)) {
                $student->name = $student_name;;
                $student->nickname = $student_name;
            }
            $student->save(false);
        }
        /*更改学员的年龄字段*/
        return \Yii::$app->user->id;//返回当前登录用户
    }

    /*
     * 根据商品id获取商品
     */
    public function getImageforgood($goodid = 0)
    {
        $good = Goods::findOne($goodid);
        $pic = "/images/ny.png";
        if (empty($good)) {
            return "/images/ny.png";
        } else {
            $teacher_id = GoodsTeacher::findOne(['goods_id' => $goodid]);
            if ($teacher_id != null) {
                $teacher = Teacher::findOne(['id' => $teacher_id->teacher_id]);
                if (!empty($teacher) && !empty($teacher->img)) {
                    $pic = $teacher->img;
                } else {
                    $mechanic_id = $good['mechanic_id'];
                    if (!empty($mechanic_id)) {
                        $mechanic = Mechanic::findOne($mechanic_id);
                        if (!empty($mechanic) && !empty($mechanic->picture)) {
                            $pic = $mechanic->picture;
                        } else {
                            $cat_id = $good['cat_id'];
                            $cat = Cate::findOne($cat_id);
                            if (!empty($cat) && !empty($cat->mobile_image)) {//category有
                                $pic = $cat->mobile_image;
                            }
                        }
                    } else {
                        $cat_id = $good['cat_id'];
                        $cat = Cate::findOne($cat_id);
                        if (!empty($cat) && !empty($cat->mobile_image)) {//category有
                            $pic = $cat->mobile_image;
                        }
                    }

                }
            } else {
                $mechanic_id = $good['mechanic_id'];
                if (!empty($mechanic_id)) {
                    $mechanic = Mechanic::findOne($mechanic_id);
                    if (!empty($mechanic) && !empty($mechanic->picture)) {
                        $pic = $mechanic->picture;
                    } else {
                        $cat_id = $good['cat_id'];
                        $cat = Cate::findOne($cat_id);
                        if (!empty($cat) && !empty($cat->mobile_image)) {//category有
                            $pic = $cat->mobile_image;
                        }
                    }
                } else {
                    $cat_id = $good['cat_id'];
                    $cat = Cate::findOne($cat_id);
                    if (!empty($cat) && !empty($cat->mobile_image)) {//category有
                        $pic = $cat->mobile_image;
                    }
                }
            }
        }
        return $pic;
    }

    public function getGoodsclasstime($goods_attr_times)
    {
        $result_arr = [];
        if (!empty($goods_attr_times)) {
            foreach ($goods_attr_times as $good_time) {
                $gtime = '';
                if (!empty($good_time['class_day'])) {
                    $class_day = $this->getClassday($good_time['class_day']);
                    $gtime .= $class_day;
                } else {
                    $gtime .= '未知';
                }
                if (empty($good_time['start_time'])) {
                    $good_time['start_time'] = '00:00';
                }
                if (empty($good_time['end_time'])) {
                    $good_time['end_time'] = '00:00';
                }
                $class_starttime_int = (int)str_replace(":", "", $good_time['start_time']);
                $class_endtime_int = (int)str_replace(":", "", $good_time['end_time']);
                $daymode = '上午';
                if ($class_endtime_int <= 1200) {
                    $daymode = '上午';
                } elseif ($class_starttime_int > 1200) {
                    $daymode = '下午';
                }
                $gtime .= ' ' . $daymode . $good_time['start_time'] . '-' . $good_time['end_time'];
                $result_arr[] = $gtime;
            }
        }
        return $result_arr;
    }

    public function getClassday($value = 0)
    {
        switch ($value) {
            case 1:
                return '星期一';
                break;
            case 2:
                return '星期二';
                break;
            case 3:
                return '星期三';
                break;
            case 4:
                return '星期四';
                break;
            case 5:
                return '星期五';
                break;
            case 6:
                return '星期六';
                break;
            case 7:
                return '星期日';
                break;
            default:
                return '未知';
        }
        return '未知';
    }

    public function getGoodsclasstimeforapi($goods_attr_times)
    {
        $result_arr = [];
        if (!empty($goods_attr_times)) {
            foreach ($goods_attr_times as $good_time) {
                $gtime = '';
                if (!empty($good_time['class_day'])) {
                    $class_day = $this->getClassdayforapi($good_time['class_day']);
                    $gtime .= $class_day;
                } else {
                    $gtime .= '未知';
                }
                if (empty($good_time['start_time'])) {
                    $good_time['start_time'] = '00:00';
                }
                if (empty($good_time['end_time'])) {
                    $good_time['end_time'] = '00:00';
                }
                $gtime .= ' ' . $good_time['start_time'] . '-' . $good_time['end_time'];
                $result_arr[] = $gtime;
            }
        }
        return $result_arr;
    }

    public function getClassdayforapi($value = 0)
    {
        switch ($value) {
            case 1:
                return '周一';
                break;
            case 2:
                return '周二';
                break;
            case 3:
                return '周三';
                break;
            case 4:
                return '周四';
                break;
            case 5:
                return '周五';
                break;
            case 6:
                return '周六';
                break;
            case 7:
                return '周日';
                break;
            default:
                return '未知';
        }
        return '未知';
    }

    /*
     * 获取出生年份数组
     */
    public function bornedYears($start_year, $end_year)
    {
        if (empty($start_year)) {
            $start_year = '1998';
        }
        if (empty($end_year)) {
            $end_year = '2013';
        }
        if ($start_year > $end_year) {
            return null;
        }
        $result = [];
        for ($start_year; $start_year <= $end_year; $start_year++) {
            $result[$start_year] = $start_year;
        }
        return $result;
    }

    /*
     * 添加订单统计中间表
     */
    public function addOrderAssociateStat($order_items, $customer_id = null)
    {
        if (empty($customer_id)) {
            $customer_id = \Yii::$app->user->id;
            if (empty($customer_id)) {
                return null;
            }
        }
        //\Yii::error('customer_id:' . $customer_id);
        $student = Student::find()->where(['customer_id' => $customer_id])->one();
        $student_id = null;
        $student_age = 0;
        if (!empty($student)) {
            $student_id = $student->id;
            if (!empty($student->age) && intval($student->age) > 0) {
                $year = intval(date('Y'));
                $student_age = $year - intval($student->age);
            }
        }
        $card_attr = CardAttr::findOne(['customer_id' => $customer_id]);
        //\Yii::error('card_attr:');
        //\Yii::error($card_attr);
        $relation_orders = [];
        //\Yii::error('order_item:');
        //\Yii::error($order_items);
        if (!empty($order_items)) {
            foreach ($order_items as $order_item) {
                $goodid = $order_item['goods_id'];
                $good = Goods::findOne($goodid);
                $teacher_info = GoodsAttr::findOne(['goods_id' => $goodid, 'obj_type' => 'teacher']);
                $area_info = GoodsAttr::findOne(['goods_id' => $goodid, 'obj_type' => 'region']);
                $relation_orders[] = [
                    'customer_id' => $customer_id,
                    'student_id' => $student_id,
                    'mechanic_id' => $order_item['mechanic_id'],
                    'goods_id' => $goodid,
                    'teacher_id' => $teacher_info->attribute_id,
                    'cate_id' => $good->cat_id,
                    'orders_id' => $order_item['orders_id'],
                    'orders_items_id' => $order_item['id'],
                    'status' => $order_item['status'],
                    'created_at' => time(),
                    'salesman_id' => (!empty($card_attr) && !empty($card_attr->salesman_id)) ? $card_attr->salesman_id : 0,
                    'send_type' => (!empty($card_attr) && !empty($card_attr->sendtype)) ? $card_attr->sendtype : 0,
                    'mechanic_area' => !empty($area_info->value) ? $area_info->value : '',
                    'site_id' => Fun::getSiteId(),
                    'student_age' => $student_age
                ];
            }
        }
        //\Yii::error('relation_orders:');
        //\Yii::error($relation_orders);
        if (!empty($relation_orders)) {
            \Yii::$app->db->createCommand()->batchInsert('{{%reservation}}', [
                'customer_id', 'student_id', 'mechanic_id', 'goods_id', 'teacher_id', 'cate_id', 'orders_id', 'orders_items_id', 'status', 'created_at', 'salesman_id', 'send_type', 'mechanic_area', 'site_id', 'student_age'
            ], $relation_orders)->execute();
        }
    }

    /*检测课程是否已经上到第二节课，则禁止购买*/
    public function checkCanBuyforGood($good_id)
    {
//        $result_data = (new Query())->select('cm.status as status,cl.class_date as firstlessontime, cl.status as classlesson_status')->from("{{%goods}} g")
//            ->leftJoin(['cm' => (new \yii\db\Query())->from('{{%class_manage}}')->where('is_old=0')], 'cm.associate_id=g.id')
//            ->leftJoin(['cl' => (new \yii\db\Query())->from('{{%class_lesson}}')->where(['lesson' => 2])], 'cl.class_id = cm.class_id')
//            ->where(['g.id' => $good_id])
//            ->one(Fun::getSiteDb());
//        $canbuy_good = true;
//        if ($result_data['status'] == 1) {//已经开课
//            if (!empty($result_data['firstlessontime']) && time() >= $result_data['firstlessontime']) {//当前时间大于第二节课的开课时间了，不在第二节课之前了
//                $canbuy_good = false;//不可预约
//            }
//            /*if ($result_data['classlesson_status'] != 0) {//第二节课未上课则可预约，否则不可预约
//                $canbuy_good = false;//不可预约
//            }*/
//        }
//        return $canbuy_good;
        return true;
    }

    /*广场检测是否已经上到第二节课，如果有则禁止*/
    public function checkCanBuyforSquare($good_id)
    {
        $canbuy_good=true;
        /*$result_data = (new Query())->select('cm.status as status,cl.class_date as firstlessontime, cl.status as classlesson_status')->from("{{%goods}} g")
            ->leftJoin(['cm' => (new \yii\db\Query())->from('{{%class_manage}}')->where('is_old=0')], 'cm.associate_id=g.id')
            ->leftJoin(['cl' => (new \yii\db\Query())->from('{{%class_lesson}}')->where(['lesson' => 2])], 'cl.class_id = cm.class_id')
            ->where(['in', 'g.id', $good_id])
            ->all(Fun::getSiteDb());
        $status_arr = [];
        $canbuy_good = true;
        foreach ($result_data as $key => $val) {
            if ($val['status'] == 1) {//已经开课
                if (!empty($val['firstlessontime']) && time() >= $val['firstlessontime']) {//当前时间大于第二节课的开课时间了，不在第二节课之前了
                    $status_arr[$key] = 'no';//不可预约
                } else {
                    $status_arr[$key] = 'can';
                }
            } else {
                $status_arr[$key] = 'can';
            }
        }
        if (in_array('no', $status_arr)) {
            $canbuy_good = false;
        }*/
        return $canbuy_good;
    }

    /*同类不可重复预约*/
    public function verificationCate($goods)
    {
        $site = Site::findOne(Fun::getSiteId());
        if ($site->is_buy_repeat == 1) {
            return true;
        }
        $customerId = \Yii::$app->user->id;
        $orders_ids = Orders::find()->select('id')->where(['customer_id' => $customerId, 'order_type' => 'appointment', 'is_invalid' => 0])->andWhere(['>', 'pay_status', 0])->andWhere(['not', ['status' => 2]])->column();//仅获取有效订单以及排除取消订单的判断
        $goodsids = OrdersItems::find()->select('goods_id')->where(['orders_id' => $orders_ids])->groupBy('goods_id')->column();
        $goods_list = Goods::find()->where(['id' => $goodsids, 'cat_id' => $goods->cat_id])->all();
        if ($goods_list) {
            return false;
        }
        return true;

    }

    /*
     * develop #139 未支付订单添加继续支付功能
     * 同类未付款课程是否存在
     * false: 存在未付款同类
     * true: 不存在付款同类
     */
    public function checkHavenonpayCategood($good = null)
    {
        $site = Site::findOne(Fun::getSiteId());
        if ($site->is_buy_repeat == 1) {
            //可以购买同个分类的商品
            return null;
        }
        if (!empty($good)) {
            $customerId = \Yii::$app->user->id;
            $orders_ids = Orders::find()->select('id')->where(['customer_id' => $customerId, 'order_type' => 'appointment', 'pay_status' => 0])->andWhere(['not', ['status' => 2]])->column();
            $goodsids = OrdersItems::find()->select('goods_id')->where(['orders_id' => $orders_ids])->groupBy('goods_id')->column();
            $goods_list = Goods::find()->where(['cat_id' => $good->cat_id])->andWhere(['in', 'id', $goodsids])->all();
            if (!empty($goods_list)) {
                return $goods_list;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /*
     * develop #139 未支付订单添加继续支付功能
     * 获取未付款同分类的订单然后将其状态更改为失效的
     */
    public function deactivateNopayOrders($good = null)
    {
        $site = Site::findOne(Fun::getSiteId());
        if ($site->is_buy_repeat == 1) {
            //可以购买同个分类的商品
            return null;
        }
        if (!empty($good)) {
            $customerId = \Yii::$app->user->id;
            $orders_list = Orders::find()->select('{{%orders}}.*')->joinWith('ordersItems.goods')->where(['{{%orders}}.customer_id' => $customerId, '{{%orders}}.order_type' => 'appointment', '{{%orders}}.pay_status' => 0, '{{%goods}}.cat_id' => $good->cat_id])->andWhere(['not', ['{{%orders}}.status' => 2]])->all();
            if (!empty($orders_list)) {
                return $orders_list;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

}